package com.lyf.learn.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @AUTHOR LYF
 * @DATE 2022/5/23
 * @VERSION 1.0
 * @DESC
 */
public class JmsProvider {
    private static final String CONNECT_URL = "tcp://47.98.99.88:61616";
    private static final String QUEUE_NAME1 = "queue-test-1";
    private static final String QUEUE_NAME2 = "queue-test-2";

    public static void main(String[] args) throws JMSException, InterruptedException {
        // 1.创建工厂--连接管理，结合JDBC,Redis等数据库的连接-
        ActiveMQConnectionFactory mqConnectionFactory = new ActiveMQConnectionFactory(CONNECT_URL);
        // 2.创建连接管理 -- 连接统一管理
        Connection connection = mqConnectionFactory.createConnection();

        // 3.创建session 会话，该次连接的会话--一个Connection,对应多个Session？
        // 策略在Session处定义，有AUTO_ACKNOWLEDGE 签收机制 ，TRANSACTION事务机制
        Session session1 = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        //报错:acknowledgeMode SESSION_TRANSACTED cannot be used for an non-transacted Session
        // Session session2 = connection.createSession(false,Session.SESSION_TRANSACTED);
        Session session2 = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

        // 4.创建目的地(Destination)--Queue Or Topic
        // 多个session,多个queue
        Queue queue11 = session1.createQueue(QUEUE_NAME1);
        Queue queue12 = session1.createQueue(QUEUE_NAME1);

        Queue queue21 = session2.createQueue(QUEUE_NAME1);
        Queue queue22 = session2.createQueue(QUEUE_NAME1);

        // 5.创建生产者
        MessageProducer producer11 = session1.createProducer(queue11);
        // 思考利用不同session的创建的目的地？
        // 6.创建消息--也有session来创建

        /// 7.发送
        int  n = 100,i=1;
        while(i++<n){
            TextMessage message = session1.createTextMessage("msg-test-again"+new Random().nextInt(1024));
            producer11.send(message);
            TimeUnit.SECONDS.sleep(2);
            System.out.println("send:"+message.getText());
        }

        // 8.关闭资源--
        producer11.close();
        session1.close();
        connection.close();
    }
}
